package com.qububu.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

public class CodeImgGenerater {

	private Random random = new Random();

	// Here 1 and l is not used because they hard to be distinguished.
	private char charTable[] = {'1', '2', '3', '4', '5', '6', '7', '8',
			'9',  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'm',
			'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};

	private Color getRandColor(int fc, int bc) {
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	public char[] createRandomChars() {

		int size = charTable.length;
		char[] randChars = new char[5];
		for (int i = 0; i < 5; i++) {
			randChars[i] = charTable[random.nextInt(size)];
		}

		return randChars;
	}

	public BufferedImage creatImageFromChars(char[] randChars) {

		int width = 85, height = 45;
		BufferedImage img = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = img.getGraphics();

		g.setColor(getRandColor(200, 250));
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Times New Random", Font.ITALIC, 26));
		g.setColor(getRandColor(160, 200));

		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			g.drawLine(x, y, x + xl, y + yl);
		}

		for (int i = 0; i < randChars.length; i++) {
			String rand = String.valueOf(randChars[i]);
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(rand, 3 + 15 * i, 30);
		}

		g.dispose();

		return img;

	}

}